package com.wzy.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzy.mapper.UserMapper;
import com.wzy.pojo.User;
import com.wzy.service.SendMailService;
import com.wzy.utils.JwtHelper;
import com.wzy.utils.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.http.HttpRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    SendMailService sendMailService;
    //    邮件发送的api
    @GetMapping("/sendMessage")
    public R message(@RequestParam(name = "nickname") String name, @RequestParam(name = "text") String text,
                     @RequestParam("address") String address, HttpServletRequest httpServletRequest) {
        String to = "wzy9858@qq.com";
        String subject = "你搭建的个人博客项目有人给你发了一条信息";
        //拿到发送日期
        SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = s1.format(new Date());
        //拿到设备标识符号
        String flag = httpServletRequest.getHeader("sec-ch-ua-platform");
        String textall = "以下是备注昵称为: " + name + "(相关地址为: " + address +" 设备标识为: "+ flag + " ) 发送的信息:\n" + text;
        sendMailService.sendSimpleEmail(to, subject, textall);
        return R.ok().code(200);
    }

//    //    访客用户登录 将相关信息存入数据库的api
//    @Autowired
//    UserMapper userMapper;
//
//    //得到所有用户 可以使用jwt令牌 传过来密钥
//    @GetMapping("/list")
//    public R getUsers() {
//        List<User> users = userMapper.selectList(null);
//        R ok = R.ok();
//        ok.data("users", users);
//        ok.setCode(200);
//        return ok;
//    }

    @Autowired
    UserMapper userMapper;

    @Autowired
    JwtHelper jwtHelper;

    @PostMapping("/login")
    public R login(@RequestBody User user){

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername());
        queryWrapper.eq("password",user.getPassword());

        List<User> users = userMapper.selectList(queryWrapper);


        if (users.size() == 0){
            System.out.println("11111111");
            R error = R.error();
            error.code(600);
            return error;
        }else {
            //登录成功的话 设置一下cookie
            String jwt = jwtHelper.createJwt(user.getId());
            R ok = R.ok();
            ok.data("jwt",jwt);
            System.out.println("222");
            return ok;
        }
    }



}
